#!/bin/bash

# 通过参数获取端口号
port="$1"
if [ -z "$port" ]; then
    read -p "请输入web ui端口号: " port
    if [ -z "$port" ]; then
        echo "错误：必须输入端口号！"
        exit 1
    fi
fi

# 检查并清除已有配置
if grep -q "^client_dashboard_addr:" /usr/local/etc/cpolar/cpolar.yml; then
    # 删除已存在的配置行
    sudo sed -i '/^client_dashboard_addr:/d' /usr/local/etc/cpolar/cpolar.yml
fi

# 在文件最顶部添加dashboard配置
sudo sed -i "1i\client_dashboard_addr: 0.0.0.0:${port}\n" /usr/local/etc/cpolar/cpolar.yml

# 重启cpolar服务使配置生效
sudo systemctl restart cpolar
echo "已成功修改web ui 的端口为${port}!"

# 脚本执行完成后自删除
script_path=$(realpath "$0")
rm -f "$script_path"